<template>
  <div class="register-form">
    <el-form ref="registerForm" :model="registerForm" :rules="rules" hide-required-asterisk>
      <el-form-item prop="org">
        <el-input v-model="registerForm.org" placeholder="请输入组织机构" :maxlength="30">
          <i slot="prefix" class="el-icon-office-building perfix-icon"></i>
        </el-input>
      </el-form-item>
      <el-form-item prop="phone" class="user">
        <el-input
          v-model="registerForm.phone"
          :maxlength="11"
          name="phone"
          placeholder="请输入手机号"
          class="phone-input">
          <template slot="prefix">
            <i class="el-icon-mobile-phone perfix-icon"></i>
            <span class="phone-prefix">+86</span>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item prop="code">
        <el-input v-model="registerForm.code" type="text" :maxlength="6" placeholder="6位短信验证码" class="code-input">
          <i slot="prefix" class="iconfont icon-password perfix-icon"></i>
          <template slot="append">
            <el-button :loading="coding" type="primary" @click="getCode">
              {{ codeBtnDisplay }}
            </el-button>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item prop="password">
        <el-popover trigger="focus" :placement="placement" popper-class="password-tips-popover">
          <div class="password-tip-con">
            <p class="tips-title">密码设置规则</p>
            <p class="tips-con">1. 8~16位数字、字母和特殊符号的组合</p>
            <p class="tips-con">2. 特殊字符包含：!@#$%^&*+=_.()&lt;&gt;?</p>
          </div>
          <el-input :type="inpType1" v-model="registerForm.password" slot="reference" placeholder="请设置密码">
            <i slot="prefix" class="el-icon-lock perfix-icon"></i>
            <span slot="suffix" class="pwd-eye-view" @click.stop="togglePwdDisplay('1')">
              <i class="iconfont icon-biyan" v-show="inpType1 === 'password'"></i>
              <i class="iconfont icon-zhengyan" v-show="inpType1 === 'text'"></i>
            </span>
          </el-input>
        </el-popover>
      </el-form-item>
      <el-form-item prop="password2">
        <el-popover trigger="focus" :placement="placement" popper-class="password-tips-popover">
          <div class="password-tip-con">
            <p class="tips-title">密码设置规则</p>
            <p class="tips-con">1. 8~16位数字、字母和特殊符号的组合</p>
            <p class="tips-con">2. 特殊字符包含：!@#$%^&*+=_.()&lt;&gt;?</p>
          </div>
          <el-input :type="inpType2" v-model="registerForm.password2" slot="reference" placeholder="请确认密码">
            <i slot="prefix" class="el-icon-lock perfix-icon"></i>
            <span slot="suffix" class="pwd-eye-view" @click.stop="togglePwdDisplay('2')">
              <i class="iconfont icon-biyan" v-show="inpType2 === 'password'"></i>
              <i class="iconfont icon-zhengyan" v-show="inpType2 === 'text'"></i>
            </span>
          </el-input>
        </el-popover>
      </el-form-item>
      <div class="privacy-service-box">
        <div class="agree-checkbox">
          <el-checkbox v-model="agreeService"></el-checkbox>
          <p class="tips-txt">
            我已阅读并同意
            <el-button type="text" @click.stop="toHelp('privacy')">《隐私政策》</el-button>
            和
            <el-button type="text" @click.stop="toHelp('service')">《用户服务协议》</el-button>
          </p>
        </div>
        <div v-if="isDirty && !agreeService" class="err-tips">请确认接受隐私政策及用户服务协议</div>
      </div>
      <div class="register-btn" @click.stop="registerUser">注 册</div>
    </el-form>
  </div>
</template>
<script>
import { phoneReg, pwdReg2 } from '@utility/regExps.js'
// import { getIdentifyingCode } from '@api/modules/user.js'
export default {
  name: 'RegisterForm',
  emits: ['register-success'],
  data() {
    const checkPhone = (rule, value, cb) => {
      if (!value) {
        cb(new Error('手机号不能为空'))
      } else if (phoneReg.test(value)) {
        cb()
      } else {
        cb(new Error('请输入有效的手机号'))
      }
    }
    const checkCode = (rule, val, cb) => {
      if (!val) {
        cb(new Error('验证码不能为空'))
      } else if (/^\d{6}$/.test(val)) {
        cb()
      } else {
        cb(new Error('验证码不正确'))
      }
    }
    const checkPwd = (rule, value, cb) => {
      if (!value) {
        cb(new Error('密码不能为空'))
      } else if (pwdReg2.test(value)) {
        cb()
      } else {
        cb(new Error('8~16位数字、字母和特殊符号的组合'))
      }
    }
    const checkPwd2 = (rule, value, cb) => {
      if (!value) {
        cb(new Error('密码不能为空'))
      } else if (pwdReg2.test(value)) {
        if (this.registerForm.password === value) {
          cb()
        } else {
          cb(new Error('两次密码不一致'))
        }
      } else {
        cb(new Error('8~16位数字、字母和特殊符号的组合'))
      }
    }
    return {
      registerForm: {
        org: '',
        phone: '',
        code: '',
        password: '',
        password2: '',
      },
      rules: {
        org: [{ required: true, message: '组织结构不能为空', trigger: 'blur' }],
        phone: [{ required: true, validator: checkPhone, trigger: 'blur' }],
        code: [{ required: true, validator: checkCode, trigger: 'blur' }],
        password: [{ required: true, validator: checkPwd, trigger: 'blur' }],
        password2: [{ required: true, validator: checkPwd2, trigger: 'blur' }],
      },
      sendCodeStatus: 'init',
      coding: false,
      cutdownSec: 0,
      cutdownTimer: null,
      inpType1: 'password',
      inpType2: 'password',
      placement: 'right',
      agreeService: false,
      isDirty: false,
    }
  },
  watch: {
    agreeService(bool) {
      this.isDirty = false
    },
  },
  computed: {
    codeBtnDisplay() {
      if (this.sendCodeStatus === 'init') {
        return '发送验证码'
      } else if (this.sendCodeStatus === 'send') {
        return this.cutdownSec + ' 秒'
      }
      return '重新发送'
    },
  },
  mounted() {
    this.watchWindowSize()
    window.addEventListener('resize', this.watchWindowSize)
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.watchWindowSize)
  },
  methods: {
    watchWindowSize() {
      const wW = document.documentElement.clientWidth
      if (wW > 750) {
        this.placement = 'right'
      } else {
        this.placement = 'top'
      }
    },
    getCode() {
      if (this.coding || this.sendCodeStatus === 'send') {
        return false
      }
      let validPhone = true
      this.$refs.registerForm.validateField('phone', err => {
        validPhone = !err
      })
      if (validPhone) {
        this.coding = true
        // getIdentifyingCode(this.registerForm.phone)
        //   .then(res => {
        //     this.coding = false
        //     if (res.status === 200) {
        //       this.startCutdown()
        //     }
        //   })
        //   .catch(() => {
        //     this.coding = false
        //   })
      }
    },
    startCutdown() {
      this.clearCutdownTimer()
      this.sendCodeStatus = 'send'
      this.cutdownSec = 60
      this.cutdownTimer = setInterval(() => {
        this.cutdownSec--
        if (this.cutdownSec <= 0) {
          this.clearCutdownTimer()
          this.sendCodeStatus = 'retry'
        }
      }, 1000)
    },
    clearCutdownTimer() {
      if (this.cutdownTimer) {
        clearInterval(this.cutdownTimer)
      }
    },
    registerUser() {
      if (!this.agreeService) {
        this.isDirty = true
        return false
      }
      this.$refs.registerForm.validate(async valid => {
        if (valid) {
          this.$emit('register', this.registerForm)
        }
      })
    },
    togglePwdDisplay(type) {
      const inpType = `inpType${type}`
      this[inpType] = this[inpType] === 'password' ? 'text' : 'password'
    },
    toHelp(path) {
      const routeData = this.$router.resolve({
        path: `/${path}`,
      })
      window.open(routeData.href, '_blank')
    },
  },
}
</script>
<style lang="scss" scoped>
.register-form {
  width: 100%;

  .perfix-icon {
    margin-left: 10px;
    color: #1b8aee;
  }

  .pwd-eye-view {
    cursor: pointer;
    display: inline-block;
    width: 50px;
    height: 100%;
    line-height: 42px;
  }

  i {
    font-size: 18px;
    line-height: 42px;
    color: #a8d2f7;
  }

  ::v-deep .el-input {
    width: 100%;
    height: 42px;
    background: #ffffff;
    border-radius: 4px;

    input {
      border-radius: 4px !important;
      height: 100%;
      padding-left: 50px;
      padding-right: 50px;
      border-color: #a8d2f7;

      &:focus {
        border-color: #1b8aee;
        box-shadow: 0px 3px 9px 1px rgba(113, 145, 181, 0.5);
      }
    }

    &.phone-input {
      input {
        padding-left: 80px;
      }
      .phone-prefix {
        padding-left: 5px;
      }
      .el-input__prefix {
        display: flex;
        align-items: center;
      }
    }

    &.code-input input {
      border-top-right-radius: 0px !important;
      border-bottom-right-radius: 0px !important;
    }

    .el-input-group__append {
      color: #fff;
      background: linear-gradient(0deg, #0074f4 0%, #2099ff 100%);
      border-right: none;
      border-top-right-radius: 4px !important;
      border-bottom-right-radius: 4px !important;

      .el-button.is-loading {
        height: 100%;
      }
    }
  }

  .privacy-service-box {
    .agree-checkbox {
      display: inline-flex;
      align-items: center;
      .tips-txt {
        margin-left: 10px;
        font-size: 13px;
        .el-button {
          font-size: 13px;
          margin-left: 0px;
          padding: 0;
        }
      }
    }
    .err-tips {
      margin-top: 4px;
      font-size: 12px;
      line-height: 1;
      color: #fc6969;
    }
  }

  .register-btn {
    width: 100%;
    height: 42px;
    margin-top: 30px;
    background: linear-gradient(0deg, #0074f4 0%, #2099ff 100%);
    border-radius: 4px;
    font-size: 18px;
    line-height: 42px;
    font-weight: 800;
    text-align: center;
    color: #ffffff;
    cursor: pointer;
  }
}
</style>
<style lang="scss">
.el-popover {
  &.password-tips-popover {
    .password-tip-con {
      .tips-title {
        font-size: 15px;
        list-style: 24px;
        margin-bottom: 10px;
        color: #333;
      }

      .tips-con {
        font-size: 13px;
        list-style: 20px;
        margin-bottom: 5px;
        color: #666;
      }
    }
  }
}
</style>
